//
//  ScrollLabelView.m
//  SortDictTest
//
//  Created by lilubin on 15/7/16.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ScrollLabelView.h"
#import <Foundation/Foundation.h>

#define Banner_StartTag     100
#define Label_Tag  200

@interface ScrollLabelView ()
{
    // 下载统计
    NSInteger totalCount;
}

//@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, assign) BOOL enableRolling;


- (void)refreshScrollView;

- (NSInteger)getPageIndex:(NSInteger)index;
- (NSArray *)getDisplayImagesWithPageIndex:(NSInteger)pageIndex;


@end

@implementation ScrollLabelView
@synthesize delegate;

@synthesize imagesArray;
@synthesize scrollDirection;

//@synthesize pageControl;

- (void)dealloc
{
    delegate = nil;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
    //    [[SDWebImageManager sharedManager] cancelForDelegate:self];
    
    //[imagesArray release];
    //[pageControl release];
    
    //[super dealloc];
}

- (id)initWithFrame:(CGRect)frame scrollDirection:(LabelViewScrollDirection)direction images:(NSArray *)images
{
    self = [super initWithFrame:frame];
    
    if(self)
    {
        self.imagesArray = [[NSArray alloc] initWithArray:images];
        
        self.scrollDirection = direction;
        
        totalPage = imagesArray.count;
        totalCount = totalPage;
        // 显示的是图片数组里的第一张图片
        // 和数组是+1关系
        curPage = 1;
        
        scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        [self addSubview:scrollView];
        
        
        
        // 在水平方向滚动
        if(scrollDirection == LabelScrollDirectionLandscape)
        {
            scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3,
                                                scrollView.frame.size.height);
            //            NSLog(@"scroll.contentSize:%@", NSStringFromCGSize(scrollView.contentSize));
            
        }
        // 在垂直方向滚动
        else if(scrollDirection == LabelScrollDirectionPortait)
        {
            scrollView.contentSize = CGSizeMake(scrollView.frame.size.width,
                                                scrollView.frame.size.height * 3);
        }
        
        
        for (NSInteger i = 0; i < 3; i++)
        {
            UIView *containView = [[UIView alloc] initWithFrame:scrollView.bounds];
            containView.backgroundColor = [UIColor clearColor];
            
            containView.userInteractionEnabled = YES;
            containView.tag = Banner_StartTag+i;
            
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
            [containView addGestureRecognizer:singleTap];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, containView.frame.size.width, containView.frame.size.height)];
            [label setFont:[UIFont fontWithName:@"Heiti SC" size:15]];
            UIColor *bgColor = [UIColor colorWithWhite:1.0 alpha:0.9];
            [label setBackgroundColor:bgColor];
            
            label.textAlignment = NSTextAlignmentCenter;
            //            label.backgroundColor = [UIColor clearColor];
            if (i == 0) {
                label.text = images[i][@"title"];
            }
            label.tag = Label_Tag+i;
            [containView addSubview:label];
            
            // 水平滚动
            
            if(scrollDirection == LabelScrollDirectionLandscape)
            {
                containView.frame = CGRectOffset(containView.frame, scrollView.frame.size.width * i, 0);
            }
            // 垂直滚动
            else if(scrollDirection == LabelScrollDirectionPortait)
            {
                containView.frame = CGRectOffset(containView.frame, 0, scrollView.frame.size.height * i);
            }
            
            [scrollView addSubview:containView];
            
        }
        
    }
    
    return self;
}

- (void)reloadBannerWithData:(NSArray *)images
{
    if (self.enableRolling)
    {
        [self stopRolling];
    }
    
    self.imagesArray = [[NSArray alloc] initWithArray:images];
    
    totalPage = imagesArray.count;
    totalCount = totalPage;
    curPage = 1;
}

- (void)setSquare:(NSInteger)asquare
{
    if (scrollView)
    {
        scrollView.layer.cornerRadius = asquare;
        if (asquare == 0)
        {
            scrollView.layer.masksToBounds = NO;
        }
        else
        {
            scrollView.layer.masksToBounds = YES;
        }
    }
}

- (void)showClose:(BOOL)show
{
    if (show)
    {
        if (!BannerCloseButton)
        {
            BannerCloseButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [BannerCloseButton setFrame:CGRectMake(self.bounds.size.width-40, 0, 40, 40)];
            [BannerCloseButton setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
            [BannerCloseButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
            [BannerCloseButton addTarget:self action:@selector(closeBanner) forControlEvents:UIControlEventTouchUpInside];
            [BannerCloseButton setImage:[UIImage imageNamed:@"banner_close"] forState:UIControlStateNormal];
            BannerCloseButton.exclusiveTouch = YES;
            [self addSubview:BannerCloseButton];
        }
        
        BannerCloseButton.hidden = NO;
    }
    else
    {
        if (BannerCloseButton)
        {
            BannerCloseButton.hidden = YES;
        }
    }
}

- (void)closeBanner
{
    [self stopRolling];
    
    if ([self.delegate respondsToSelector:@selector(labelViewdidClosed:)])
    {
        [self.delegate labelViewdidClosed:self];
    }
}

#pragma mark - Custom Method

- (void)startDownloadImage
{
    //取消已加入的延迟线程
    if (self.enableRolling)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
    }
    /*
     [[SDWebImageManager sharedManager] cancelForDelegate:self];
     
     for (NSInteger i=0; i<self.imagesArray.count; ++i)
     {
     NSDictionary *dic = [self.imagesArray objectAtIndex:i];
     NSString *url = [dic objectForKey:@"img_url"];
     
     if ([self urlIsNotEmpty:url])
     {
     [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:url] delegate:self];
     }
     }
     */
}

- (BOOL)urlIsNotEmpty:(NSString *)url
{
    return !(url == nil
             || [url isKindOfClass:[NSNull class]]
             || ([url respondsToSelector:@selector(length)]
                 && [(NSData *)url length] == 0));
}


- (void)refreshScrollView
{
    
    NSArray *curimageUrls = [self getDisplayImagesWithPageIndex:curPage];
    
    for (NSInteger i = 0; i < 3; i++)
    {
        UIView *labelView = (UIView *)[scrollView viewWithTag:Banner_StartTag+i];
        UILabel *label = (UILabel *)[labelView viewWithTag:Label_Tag+i];
        label.text = curimageUrls[i][@"title"];
        
        //        NSLog(@"images data:%@", curimageUrls[i]);
        
    }
    
    // 水平滚动
    if (scrollDirection == LabelScrollDirectionLandscape)
    {
        scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0);
    }
    // 垂直滚动
    else if (scrollDirection == LabelScrollDirectionPortait)
    {
        scrollView.contentOffset = CGPointMake(0, scrollView.frame.size.height);
    }
    
    //    self.pageControl.currentPage = curPage-1;
    
}

- (NSArray *)getDisplayImagesWithPageIndex:(NSInteger)page
{
    NSInteger pre = [self getPageIndex:curPage-1];
    NSInteger last = [self getPageIndex:curPage+1];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:0];
    
    [images addObject:[imagesArray objectAtIndex:pre-1]];
    [images addObject:[imagesArray objectAtIndex:curPage-1]];
    [images addObject:[imagesArray objectAtIndex:last-1]];
    
    return images;
}

- (NSInteger)getPageIndex:(NSInteger)index
{
    // value＝1为第一张，value = 0为前面一张
    if (index == 0)
    {
        index = totalPage;
    }
    
    if (index == totalPage + 1)
    {
        index = 1;
    }
    
    return index;
}


#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    NSInteger x = aScrollView.contentOffset.x;
    NSInteger y = aScrollView.contentOffset.y;
    
    //取消已加入的延迟线程
    if (self.enableRolling)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
    }
    
    // 水平滚动
    if(scrollDirection == LabelScrollDirectionLandscape)
    {
        // 往下翻一张
        if (x >= 2 * scrollView.frame.size.width)
        {
            curPage = [self getPageIndex:curPage+1];
            [self refreshScrollView];
        }
        
        if (x <= 0)
        {
            curPage = [self getPageIndex:curPage-1];
            [self refreshScrollView];
        }
    }
    // 垂直滚动
    else if(scrollDirection == LabelScrollDirectionPortait)
    {
        // 往下翻一张
        if (y >= 2 * scrollView.frame.size.height)
        {
            curPage = [self getPageIndex:curPage+1];
            [self refreshScrollView];
        }
        
        if (y <= 0)
        {
            curPage = [self getPageIndex:curPage-1];
            [self refreshScrollView];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)aScrollView
{
    // 水平滚动
    if (scrollDirection == LabelScrollDirectionLandscape)
    {
        scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0);
    }
    // 垂直滚动
    else if (scrollDirection == LabelScrollDirectionPortait)
    {
        scrollView.contentOffset = CGPointMake(0, scrollView.frame.size.height);
    }
    
    if (self.enableRolling)
    {
        //NSLog(@"scrollViewDidEndDecelerating performSelector");
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
        [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.rollingDelayTime inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    }
}

#pragma mark -
#pragma mark Rolling

- (void)startRolling
{
    if (![self arrayIsNotEmpty:self.imagesArray] || self.imagesArray.count == 1)
    {
        return;
    }
    
    [self stopRolling];
    
    self.enableRolling = YES;
    [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.rollingDelayTime];
}

- (BOOL)arrayIsNotEmpty:(NSArray *)array
{
    return !(array == nil
             || [array isKindOfClass:[NSNull class]]
             || ([array respondsToSelector:@selector(count)]
                 && [array count] == 0));
}

- (void)stopRolling
{
    self.enableRolling = NO;
    //取消已加入的延迟线程
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
}

- (void)rollingScrollAction
{
    //NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
    
    [UIView animateWithDuration:0.25 animations:^{
        // 水平滚动
        if(scrollDirection == LabelScrollDirectionLandscape)
        {
            scrollView.contentOffset = CGPointMake(1.99*scrollView.frame.size.width, 0);
        }
        // 垂直滚动
        else if(scrollDirection == LabelScrollDirectionPortait)
        {
            scrollView.contentOffset = CGPointMake(0, 1.99*scrollView.frame.size.height);
        }
        //NSLog(@"%@", NSStringFromCGPoint(scrollView.contentOffset));
    } completion:^(BOOL finished) {
        if (finished)
        {
            curPage = [self getPageIndex:curPage+1];
            [self refreshScrollView];
            
            if (self.enableRolling)
            {
                //NSLog(@"rollingScrollAction performSelector");
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
                [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.rollingDelayTime inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
            }
        }
    }];
}

#pragma mark - SDWebImageManager Delegate
/*
 - (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
 {
 totalCount--;
 
 if (totalCount == 0)
 {
 curPage = 1;
 [self refreshScrollView];
 
 if ([self.delegate respondsToSelector:@selector(labelCachedDidFinish:)])
 {
 [self.delegate labelCachedDidFinish:self];
 }
 }
 }*/


#pragma mark -
#pragma mark action

- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if ([delegate respondsToSelector:@selector(labelView:didSelectlabelView:withData:)])
    {
        [delegate labelView:self didSelectlabelView:curPage-1 withData:[self.imagesArray objectAtIndex:curPage-1]];
    }
}



@end
